package com.jgzx.utils;

import cn.hutool.core.collection.CollUtil;
import com.jgzx.domain.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jackesy
 * @className: TreeUtil
 * @description: 树形结构工具类
 * @create 2021/2/2 19:54
 **/
public class TreeUtil {

    public static final Long PID = 1L;

    /**
     * 两层循环实现建树
     */
    public static <T extends TreeNode> List<T> bulid(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<>();
        if(CollUtil.isNotEmpty(treeNodes)){
            for (T treeNode : treeNodes) {
                treeNode.setLeaf_flag(true);
                if (root.toString().equals(treeNode.getP_id().toString())) {
                    trees.add(treeNode);
                }
                for (T it : treeNodes) {
                    if (it.getP_id().toString().equals(treeNode.getId().toString())) {
                        if (treeNode.getChildren() == null) {
                            treeNode.setChildren(new ArrayList<>());
                        }
                        treeNode.add(it);
                        treeNode.setLeaf_flag(false);
                    }
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        if(CollUtil.isNotEmpty(treeNodes)){
            for (T treeNode : treeNodes) {
                if (root.toString().equals(treeNode.getP_id().toString())) {
                    trees.add(findChildren(treeNode, treeNodes));
                }
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().toString().equals(it.getP_id().toString())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
